/*
 * ACEDrawingView: https://github.com/acerbetti/ACEDrawingView
 *
 * Copyright (c) 2013 Stefano Acerbetti
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

#import "ACEDrawingView.h"
#import "ACEDrawingTools.h"
#import "GMFTextView.h"

#import <QuartzCore/QuartzCore.h>

#define kDefaultLineColor       [UIColor blackColor]
#define kDefaultLineWidth       10.0f;
#define kDefaultLineAlpha       1.0f
#define kDefaultMoveSpacing		20.0f

// experimental code
#define PARTIAL_REDRAW          0

@interface ACEDrawingView ()
//@property (nonatomic, strong) NSMutableArray *pathArray;
//@property (nonatomic, strong) NSMutableArray *bufferArray;
@property (nonatomic, strong) id<ACEDrawingTool> currentTool;
@property (nonatomic, strong) UIImage *image;

//@property(nonatomic,strong)UITextView *currentText;
@property(nonatomic,strong)UIView *curentView;
@property(nonatomic)CGFloat x;
@property(nonatomic)CGFloat y;

@end

#pragma mark -

@implementation ACEDrawingView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configure];
        self.textNormalColor = kColorDefaultBlue;
        
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chageColor:) name:@"changeColor" object:nil];
        
        //        /// 垃圾桶按钮
        //        UIButton *btnTrash = [[UIButton alloc] initWithFrame:CGRectMake(screenW - 60, 80, fltButtonWidth, fltButtonWidth)];
        //        [btnTrash setImage:[UIImage imageNamed:@"trash"] forState:UIControlStateNormal];
        //        [btnTrash addTarget:self action:@selector(trashButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        ////        btnTrash.hidden = YES;
        //        [self addSubview:btnTrash];
        //        self.btnTrash = btnTrash;
        
        //        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSelf)];
        //        [self addGestureRecognizer:tap];
        
        //        UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTap:)];
        //        doubleTapGesture.numberOfTapsRequired = 2;
        //        doubleTapGesture.numberOfTouchesRequired = 1;
        //        [self addGestureRecognizer:doubleTapGesture];
        
    }
    self.userInteractionEnabled = YES;
    self.multipleTouchEnabled = YES;
    self.isdrawing=NO;
    _canDraw = YES;
    return self;
}


- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self configure];
    }
    return self;
}


- (void)deleteTheSelectedDrawingTool
{
    [self.currentTool setselect:0];
    [self.bufferArray removeAllObjects];
    if(self.currentTool) {
        id<ACEDrawingTool> tool=[self.currentTool Copy];
        [tool setIsDel:1];
        [tool setOriginal:self.currentTool];
        [self.pathArray addObject:tool];
        [self.currentTool setIsDel:1];
    }
    self.currentTool=nil;
    [self updateCacheImage:YES];
    [self setNeedsDisplay];
}


- (void)changeColor:(UIColor *)color
{
    if (self.currentTool)
    {
        id<ACEDrawingTool> tool=[self.currentTool Copy];
        [tool setIsDel:0];
        [self.currentTool setIsDel:1];
        [tool setOriginal:self.currentTool];
        [self.pathArray addObject:tool];
        self.currentTool=tool;
        
        self.currentTool.lineColor = color;
        
        [self updateCacheImage:YES];
        [self setNeedsDisplay];
    }
    
}


- (void)configure
{
    // init the private arrays
    self.pathArray = [NSMutableArray array];
    self.bufferArray = [NSMutableArray array];
    
    // set the default values for the public properties
    self.lineColor = [UIColor blueColor];
    self.lineWidth = kDefaultLineWidth;
    self.lineAlpha = kDefaultLineAlpha;
    
    // set the transparent background
    self.backgroundColor = [UIColor clearColor];
}


#pragma mark - Drawing

- (void)drawRect:(CGRect)rect
{
#if PARTIAL_REDRAW
    // TODO: draw only the updated part of the image
    [self drawPath];
#else
    [self.image drawInRect:self.bounds];
    // [self.currentTool draw];
#endif
}

- (void)updateCacheImage:(BOOL)redraw
{
    // init a context
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    
    if (redraw) {
        // erase the previous image
        self.image = nil;
        
        // I need to redraw all the lines
        for (id<ACEDrawingTool> tool in self.pathArray) {
            if([tool isDel]==0)
                [tool draw];
        }
        
    } else {
        // set the draw point
        [self.image drawAtPoint:CGPointZero];
        [self.currentTool draw];
    }
    
    // store the image
    self.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

- (id<ACEDrawingTool>)toolWithCurrentSettings
{
    switch (self.drawTool) {
        case ACEDrawingToolTypePen:
        {
            return ACE_AUTORELEASE([ACEDrawingPenTool new]);
        }
            
        case ACEDrawingToolTypeLine:
        {
            return ACE_AUTORELEASE([ACEDrawingLineTool new]);
        }
        case ACEDrawingToolTypeArrow:
        {
            return ACE_AUTORELEASE([ACEDrawingArrowTool new]);
        }
        case ACEDrawingToolTypeRectagleStroke:
        {
            ACEDrawingRectangleTool *tool = ACE_AUTORELEASE([ACEDrawingRectangleTool new]);
            tool.fill = NO;
            return tool;
        }
            
        case ACEDrawingToolTypeRectagleFill:
        {
            ACEDrawingRectangleTool *tool = ACE_AUTORELEASE([ACEDrawingRectangleTool new]);
            tool.fill = YES;
            return tool;
        }
            
        case ACEDrawingToolTypeEllipseStroke:
        {
            ACEDrawingEllipseTool *tool = ACE_AUTORELEASE([ACEDrawingEllipseTool new]);
            tool.fill = NO;
            return tool;
        }
            
        case ACEDrawingToolTypeEllipseFill:
        {
            ACEDrawingEllipseTool *tool = ACE_AUTORELEASE([ACEDrawingEllipseTool new]);
            tool.fill = YES;
            return tool;
        }
    }
}

#pragma mark - Touch Methods

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //    UITouch *touch = [touches anyObject];
    //    //        CGPoint touchPoint = [touch locationInView:self];
    //
    //    if (touch.tapCount == 2)
    //    {
    //        NSLog(@"aaa");
    //        if ([self.tDelegate respondsToSelector:@selector(drawingViewDoubleTags:)]) {
    //            [self.tDelegate drawingViewDoubleTags:self];
    //        }
    //    }
    
    if (touches.count == 2)
    {
        if ([self.aDelegate respondsToSelector:@selector(drawingView:isOneTouch:)])
        {
            [self.aDelegate drawingView:self isOneTouch:NO];
        }
        self.currentTool=nil;
    }
    
    else if (touches.count == 1)
    {
        
        if ([self.aDelegate respondsToSelector:@selector(drawingView:isOneTouch:)])
        {
            [self.aDelegate drawingView:self isOneTouch:YES];
        }
        
        UITouch *touch = [touches anyObject];
        
        CGPoint touchPoint = [touch locationInView:self];
        //touchPoint.x ，touchPoint.y 就是触点的坐标。
        //        NSLog(@"qqqqqqqqqqq %f %f", touchPoint.x, touchPoint.y);
        
        //        if (!_canDraw)
        //        {
        //            [self addTextWithX:touchPoint.x andY:touchPoint.y];
        //             }
        //        else

        [self tapSelf];

        
//        if ([self.lDelegate respondsToSelector:@selector(drawingView:locationX:locationY:)])
//        {
//            [self.lDelegate drawingView:self locationX:touchPoint.x locationY:touchPoint.y];
//        }
        
        
        if(self.isdrawing==YES) {
            self.iscancel=YES;
            return;
        }
        self.movemode=0;
        self.hadmove=0;
        self.isstart=YES;
        self.iscancel=NO;
        self.isdrawing=YES;
        self.currentTool=nil;
        self.startpoint=[touch locationInView:self];
        int count =self.pathArray.count;
        BOOL haveSel=NO;
        for(int i=0; i<count;i++)
        {
            id<ACEDrawingTool> cur=(id<ACEDrawingTool>)[self.pathArray objectAtIndex:i];
            if([cur isDel]==0) {
                if(haveSel==NO) {
                    self.movemode=[cur isclicked :[touch locationInView:self]];
                    [cur setselect:0];
                    if(self.movemode) {
                        haveSel=YES;
                        [cur setselect:self.movemode];
                        self.currentTool=cur;
                    }
                }
                else
                    [cur setselect:0];
            }
        }
        
        
        if(self.movemode==0)
        {
            if ([self.lDelegate respondsToSelector:@selector(drawingView:locationX:locationY:)])
            {
                
                [self.lDelegate drawingView:self locationX:touchPoint.x locationY:touchPoint.y];
                
            }
        }
        
        if ([self.sDelegate respondsToSelector:@selector(drawingView:isSelected:)])
        {
            if (_movemode != 0)
            {
                [self.sDelegate drawingView:self isSelected:YES];
            }
            else
            {
                [self.sDelegate drawingView:self isSelected:NO];
            }
        }
        
        [self updateCacheImage:YES];
        [self setNeedsDisplay];
        
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    if (_canDraw)
    {
        if (touches.count == 2)
        {
            if ([self.aDelegate respondsToSelector:@selector(drawingView:isOneTouch:)])
            {
                [self.aDelegate drawingView:self isOneTouch:NO];
            }
            self.isdrawing=YES;
        }
        
        else if (touches.count == 1)
        {
            if ([self.aDelegate respondsToSelector:@selector(drawingView:isOneTouch:)])
            {
                [self.aDelegate drawingView:self isOneTouch:YES];
            }
            
            
            // save all the touches in the path
            //        UITouch *touch = [touches anyObject];
            UITouch *touch = [[touches allObjects] objectAtIndex:0];
            
            // add the current point to the path
            CGPoint currentLocation = [touch locationInView:self];
            CGPoint previousLocation = [touch previousLocationInView:self];
            
//            CGPoint touchPoint = [touch locationInView:self];
            
//            if ([self.lDelegate respondsToSelector:@selector(drawingView:locationX:locationY:)])
//            {
//                [self.lDelegate drawingView:self locationX:touchPoint.x locationY:touchPoint.y];
//            }
            
            if(self.movemode) {
                if(self.isstart==YES) {
                    if(sqrt((currentLocation.x-self.startpoint.x)*(currentLocation.x-self.startpoint.x)+(currentLocation.y-self.startpoint.y)*(currentLocation.y-self.startpoint.y)) > kDefaultMoveSpacing) {
                        self.isstart=NO;
                        if(self.hadmove==0) {
                            id<ACEDrawingTool> tool=[self.currentTool Copy];
                            [tool setOriginal:self.currentTool];
                            [self.currentTool setIsDel:1];
                            [self.currentTool setselect:0];
                            [self.pathArray addObject:tool];
                            self.currentTool=tool;
                            self.hadmove=1;
                        }
                        if(self.movemode==1) {
                            [self.currentTool move:previousLocation to:currentLocation];
                        }
                        else if(self.movemode==2) {
                            [self.currentTool resizerightdown:previousLocation to:currentLocation];
                        }
                        else if(self.movemode==3) {
                            [self.currentTool resizeleftdown:previousLocation to:currentLocation];
                        }
                        else if(self.movemode==4) {
                            [self.currentTool resizerightup:previousLocation to:currentLocation];
                        }
                        else if(self.movemode==5) {
                            [self.currentTool resizeleftup:previousLocation to:currentLocation];
                        }
                    }
                }
                else {
                    if(self.movemode==1) {
                        [self.currentTool move:previousLocation to:currentLocation];
                    }
                    else if(self.movemode==2) {
                        [self.currentTool resizerightdown:previousLocation to:currentLocation];
                    }
                    else if(self.movemode==3) {
                        [self.currentTool resizeleftdown:previousLocation to:currentLocation];
                    }
                    else if(self.movemode==4) {
                        [self.currentTool resizerightup:previousLocation to:currentLocation];
                    }
                    else if(self.movemode==5) {
                        [self.currentTool resizeleftup:previousLocation to:currentLocation];
                    }
                }
            }
            else {
                if(self.iscancel==YES)
                    return;
//                NSLog(@"dddd %d", self.txtmode);
                if(self.txtmode)
                    return;
                if(self.isstart==YES)
                {
                    if(sqrt((currentLocation.x-self.startpoint.x)*(currentLocation.x-self.startpoint.x)+(currentLocation.y-self.startpoint.y)*(currentLocation.y-self.startpoint.y)) > kDefaultMoveSpacing) {
                        self.isstart = NO;
                        self.isdrawing=YES;
                        if(self.movemode == 0) {
                            // init the bezier path
                            self.currentTool = [self toolWithCurrentSettings];
                            self.currentTool.lineWidth = self.lineWidth;
                            self.currentTool.lineColor = self.lineColor;
                            self.currentTool.lineAlpha = self.lineAlpha;
                            [self.pathArray addObject:self.currentTool];
                            
                            // add the first touch
                            [self.currentTool setInitialPoint:self.startpoint];
                            
                            // call the delegate
                            if ([self.delegate respondsToSelector:@selector(drawingView:willBeginDrawUsingTool:)]) {
                                [self.delegate drawingView:self willBeginDrawUsingTool:self.currentTool];
                            }
                        }
                        [self.currentTool moveFromPoint:self.startpoint toPoint:currentLocation];
                    }
                }
                else
                {
                    [self.currentTool moveFromPoint:previousLocation toPoint:currentLocation];
                }
            }
            [self updateCacheImage:YES];
            [self setNeedsDisplay];
        }
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_canDraw)
    {
        self.isstart=NO;
        self.isdrawing=NO;
        if (touches.count == 2)
        {
            if ([self.aDelegate respondsToSelector:@selector(drawingView:isOneTouch:)])
            {
                [self.aDelegate drawingView:self isOneTouch:NO];
            }
        }
        
        else if (touches.count == 1)
        {
            if ([self.aDelegate respondsToSelector:@selector(drawingView:isOneTouch:)])
            {
                [self.aDelegate drawingView:self isOneTouch:YES];
            }
            
            
            
            // make sure a point is recorded
            [self touchesMoved:touches withEvent:event];
            self.hadmove=0;
            // update the image
            [self updateCacheImage:YES];
            
            // clear the redo queue
            [self.bufferArray removeAllObjects];
            
            // call the delegate
            if ([self.delegate respondsToSelector:@selector(drawingView:didEndDrawUsingTool:)]) {
                [self.delegate drawingView:self didEndDrawUsingTool:self.currentTool];
            }
        }
        if ([self.aDelegate respondsToSelector:@selector(drawingView:isOneTouch:)])
        {
            [self.aDelegate drawingView:self isOneTouch:YES];
        }
        
        UITouch *touch = [touches anyObject];
        //        CGPoint touchPoint = [touch locationInView:self];
        
        if (touch.tapCount == 2)
        {
            if ([self.delegate respondsToSelector:@selector(drawingViewDoubleTags:)]) {
                [self.tDelegate drawingViewDoubleTags:self];
            }
        }
    }
    
    _canDraw = YES;
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_canDraw)
    {
//        self.iscancel=YES;
//        self.isstart=NO;
//        if(self.isdrawing==NO) {
//            [self.currentTool setselect:0];
//            self.currentTool=nil;
//        }
//        self.isdrawing=NO;
//        [self.currentTool setselect:0];
//        [self.bufferArray removeAllObjects];
//        if(self.currentTool)
//            [self.pathArray removeObject:self.currentTool];
//        self.currentTool=nil;
//        [self updateCacheImage:YES];
//        [self setNeedsDisplay];
    }
}



#pragma mark - Actions

- (void)clear
{
    [self.currentTool setselect:0];
    self.currentTool=nil;
    [self.bufferArray removeAllObjects];
    [self.pathArray removeAllObjects];
    [self updateCacheImage:YES];
    [self setNeedsDisplay];
}


#pragma mark - Undo / Redo

- (NSUInteger)undoSteps
{
    return self.bufferArray.count;
}

- (BOOL)canUndo
{
    return self.pathArray.count > 0;
}

- (void)undoLatestStep
{
    if ([self canUndo]) {
        [self.currentTool setselect:0];
        self.currentTool=nil;
        id<ACEDrawingTool>tool = [self.pathArray lastObject];
        [self.bufferArray addObject:tool];
        
//        if (self.bufferArray.count >= _intBufferArrayMaxCount)
//        {
//            _intBufferArrayMaxCount = self.bufferArray.count;
//        }
        
        [self.pathArray removeLastObject];
        if([tool original]) {
            [[tool original] setIsDel:0];
        }
        
//        NSLog(@"ddd %d %d", self.bufferArray.count, _intBufferArrayMaxCount);
        
//        if (self.bufferArray.count != _intBufferArrayMaxCount)
//        {
//            NSLog(@"不能再后退了");
//        }
        
        [self updateCacheImage:YES];
        [self setNeedsDisplay];
    }
}

- (BOOL)canRedo
{
    return self.bufferArray.count > 0;
}

- (void)redoLatestStep
{
    if ([self canRedo]) {
        [self.currentTool setselect:0];
        self.currentTool=nil;
        id<ACEDrawingTool>tool = [self.bufferArray lastObject];
        [self.pathArray addObject:tool];
        [self.bufferArray removeLastObject];
        if([tool original])
            [[tool original] setIsDel:1];
        
//        NSLog(@"ddd %d", self.bufferArray.count);
        
//        if (self.bufferArray.count == 0)
//        {
//            NSLog(@"不能再前进了");
//        }
        
        [self updateCacheImage:YES];
        [self setNeedsDisplay];
    }
}

#if !ACE_HAS_ARC

- (void)dealloc
{
    self.pathArray = nil;
    self.bufferArray = nil;
    self.currentTool = nil;
    self.image = nil;
    [super dealloc];
}

#endif

/// -------------------- 文本框 --------------------

-(void)addTextWithX:(float)pX andY:(float)pY
{
    
    //注册通知在颜色按钮点击后出发（chageColor:）方法改变文本框字体颜色。
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chageColor:) name:@"changeColor" object:nil];
    
    //    [self tapSelf];
    
    _selectLev = 100;
    
    //            if (self.movemode != 0)
    //            {
    //                return;
    //            }
    
    GMFTextView * textBg = [[GMFTextView alloc]initWithFrame:CGRectMake(pX, pY, 30+20, 35+20)];
    [self addSubview:textBg];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panText:)];
    [textBg addGestureRecognizer:pan];
    
    UIButton *exitBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 28, 28)];
    //    sticker_close
    [exitBtn setImage:[UIImage imageNamed:@"btn_close_text"] forState:UIControlStateNormal];
    [exitBtn addTarget:self action:@selector(exitText) forControlEvents:UIControlEventTouchUpInside];
    exitBtn.tag = 11;
    [textBg addSubview:exitBtn];
    
    UITextView *text = [[UITextView alloc]initWithFrame:CGRectMake(20, 20, 30, 35)];
    text.layer.borderColor = [UIColor blackColor].CGColor;
    text.layer.borderWidth = 1;
    text.delegate = self;
    text.backgroundColor = [UIColor clearColor];
    text.textColor = kColorDefaultBlue;
    text.font = [UIFont systemFontOfSize:24];
    text.bounces = false;
    text.scrollEnabled = false;
    text.tag = ++_tagVar+100;
    if (self.textNormalColor) {
        text.textColor =   self.textNormalColor;
        
    }
    [text becomeFirstResponder];
    [textBg addSubview:text];
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
    [textBg addGestureRecognizer:pinch];
    _currentText = text;
    _curentView = textBg;
    
    
}

//-(void)addText{
//
//    [self tapSelf];
//
//    GMFTextView * textBg = [[GMFTextView alloc]initWithFrame:CGRectMake(100, 100, 30+20, 35+20)];
//    [self addSubview:textBg];
//
//    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panText:)];
//    [textBg addGestureRecognizer:pan];
//
//    UIButton *exitBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 28, 28)];
//    //    sticker_close
//    [exitBtn setImage:[UIImage imageNamed:@"btn_close_text"] forState:UIControlStateNormal];
//    [exitBtn addTarget:self action:@selector(exitText) forControlEvents:UIControlEventTouchUpInside];
//    exitBtn.tag = 11;
//    [textBg addSubview:exitBtn];
//
//
//
//    UITextView *text = [[UITextView alloc]initWithFrame:CGRectMake(20, 20, 30, 35)];
//    text.layer.borderColor = [UIColor blackColor].CGColor;
//    text.layer.borderWidth = 1;
//    text.delegate = self;
//    text.backgroundColor = [UIColor clearColor];
//    text.font = [UIFont systemFontOfSize:20];
//    text.bounces = false;
//    text.scrollEnabled = false;
//    [text becomeFirstResponder];
//    [textBg addSubview:text];
//
//    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
//    [textBg addGestureRecognizer:pinch];
//    _currentText = text;
//    _curentView = textBg;
//
//    UIButton *scaleBtn = [[UIButton alloc]initWithFrame:CGRectMake(textBg.frame.size.width, 0, 28, 28)];
//    //    sticker_close
//    [scaleBtn setImage:[UIImage imageNamed:@"btn_close_text"] forState:UIControlStateNormal];
//    [scaleBtn addTarget:self action:@selector(exitText) forControlEvents:UIControlEventTouchUpInside];
//    scaleBtn.tag = 12;
//    [_curentView addSubview:scaleBtn];
//}
//
//-(void)pinch:(UIPinchGestureRecognizer *)pinchGestureRecognizer{
//    UIView *view = pinchGestureRecognizer.view;
//    if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan || pinchGestureRecognizer.state == UIGestureRecognizerStateChanged) {
//        view.transform = CGAffineTransformScale(view.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
//        pinchGestureRecognizer.scale = 1;
//    }
//}

-(void)exitText{
    if(_currentText != nil){
        _currentText.layer.borderColor = [UIColor blackColor].CGColor;
        _currentText.layer.borderWidth = 0;
        [_currentText resignFirstResponder];
        [_currentText.superview removeFromSuperview];
        _currentText = nil;
    }
}

-(void)tapSelf{
    
    //    if (_canDraw)
    //    {
    //        return;
    //    }
    
    if(_currentText != nil){
        _currentText.layer.borderColor = [UIColor blackColor].CGColor;
        _currentText.layer.borderWidth = 0;
        [_curentView viewWithTag:11].hidden = YES;
        [_currentText resignFirstResponder];
        if (_currentText.text.length == 0) {
            [_currentText.superview removeFromSuperview];
            _currentText = nil;
        }
    }
    else{
        _currentText.layer.borderColor = [UIColor clearColor].CGColor;
        _currentText.layer.borderWidth = 0;
        [_curentView viewWithTag:11].hidden = YES;
        [_currentText resignFirstResponder];
        
    }
    
    _selectLev = 0;
}

-(void)panText:(UIPanGestureRecognizer *)sender
{
    [self fillContextFrame];
    
    if (_curentView.frame.origin.x <= 20)
    {
        [_curentView setFrame:CGRectMake(20, _curentView.frame.origin.y, _curentView.frame.size.width, _curentView.frame.size.height)];
    }
    
    CGPoint center = [sender translationInView:self];
    if (sender.state == UIGestureRecognizerStateBegan)
    {
        _x = sender.view.center.x;
        _y = sender.view.center.y;
        
    }
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        CGFloat textX = sender.view.frame.origin.x;
        CGFloat textY = sender.view.frame.origin.y;
        CGFloat textW = sender.view.frame.size.width;
        CGFloat textH = sender.view.frame.size.height;
        
        if (textX < (0-textW+10)||textY<(0-textH+10)){
            [sender.view removeFromSuperview];
            _currentText = nil;
            return;
        }
        if (textX > (self.frame.size.width-10) || textY > (self.frame.size.height-10)){
            [sender.view removeFromSuperview];
            _currentText = nil;
            return;
        }
        
        
    }
    
    /// 左边界判断
    if (center.x + _x <= sender.view.frame.size.width * 0.5)
    {
        return;
    }
    
    center = CGPointMake(center.x + _x, center.y + _y);
    sender.view.center = center;
}

//-(UIImage *)save
//{
//    [self tapSelf];
//    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0);
//    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
//    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    self.image = img;
//    for (UIView *sub in self.subviews){
//        [sub removeFromSuperview];
//    }
//    return img;
//}

- (void)chageColor:(NSNotification *)notify
{
    //通过颜色判断是否响应改变文本颜色的变化
    if (CGColorEqualToColor(_currentText.layer.borderColor, kColorPointBlue.CGColor))
    {
        _currentText.textColor = self.textNormalColor;
        
    }
    
    //    if (self.textNormalColor && (_selectLev == 1)){
    //
    //        _currentText.textColor = self.textNormalColor;
    //    }else{
    ////        _currentText.textColor = [UIColor blackColor];
    //    }
}

//- (void)chageColor:(NSNotification *)notify{
//    if (self.textNormalColor && (_selectLev == 1)){
//
//        _currentText.textColor = self.textNormalColor;
//    }else{
//        //        _currentText.textColor = [UIColor blackColor];
//    }
//}


-(void)fillContextFrame{
    
    float width0 = screenW - _curentView.frame.origin.x;
    float theWidth;
    
    if (width0 < 220)
    {
        theWidth = width0 - 15;
    }
    else
    {
        theWidth = 220;
    }
    


    CGSize size = [_currentText sizeThatFits:CGSizeMake(theWidth, 1000)];
    if (size.width < 50) {
        size.width = 50;
    }
    CGRect frame = _currentText.frame;
    frame.size = size;
    _currentText.frame = frame;
    CGRect rect =  _currentText.superview.frame;
    rect.size.width = frame.size.width+20;
    rect.size.height = frame.size.height+20;
    _currentText.superview.frame = rect;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    _isKeyboardShow = YES;
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    
    if ([self.rDelegate respondsToSelector:@selector(drawingViewReselect:)])
    {
        [self.rDelegate drawingViewReselect:self];
    }
    
//    _isKeyboardShow = YES;
    
    if (self.movemode != 0)
    {
        [self.currentTool setselect:0];
    }
    
    [self updateCacheImage:YES];
    [self setNeedsDisplay];
    
//    NSLog(@"ffff %f", textView.superview.frame.origin.y);
    
    if (textView.superview.frame.origin.y > screenH - 216 - 80)
    {
        _shouldViewMoveUp = NO;
    }
    
//    NSLog(@"should %d %d %d", _shouldViewMoveUp, textView.superview.frame.origin.y > screenH - 216 - 80, (_selectLev == 1) || (_selectLev == 100));
    
    // 当文本框在虚拟键盘位置时，把视图上移
    if ( ((_shouldViewMoveUp) || (textView.superview.frame.origin.y > screenH - 216 - 80)) && ((_selectLev == 1) || (_selectLev == 100)) )
    {
        CGFloat offset = 216 + 36;
        
        if ([self.hDelegate respondsToSelector:@selector(drawingViewHideBottom:isHidden:)])
        {
            [self.hDelegate drawingViewHideBottom:self isHidden:YES];
        }
        
        if (offset >= 0)
        {
            
            
            [UIView animateWithDuration:0.3 animations:^{
                UIViewController *vc = [self selfViewController];
                
                CGRect frame = vc.view.frame;
                frame.origin.y = -offset;
                vc.view.frame = frame;
            } completion:^(BOOL finished) {
                
            }];
            
        }
    }
    
    _currentText.layer.borderWidth = 0;
    [_curentView viewWithTag:11].hidden = YES;
    if (_currentText.tag == textView.tag) {
        if (++_selectLev == 1) {
            textView.layer.borderColor = kColorPointBlue.CGColor;
            // 选中状态，此标记用于判断状态切换
            _isRed = YES;
            if (self.textSelectColor) {
                textView.textColor = self.textSelectColor;
            }
            _currentText = textView;
            _curentView = textView.superview;
            _currentText.layer.borderWidth = 1;
            textView.layer.cornerRadius = 4;
            
            [_curentView viewWithTag:11].hidden = NO;
            return  NO;
            
        }else{
            textView.layer.borderColor = [UIColor blackColor].CGColor;
            if (self.textSelectColor) {
                textView.textColor = self.textSelectColor;
            }
            _currentText = textView;
            _curentView = textView.superview;
            _currentText.layer.borderWidth = 1;
            
            [_curentView viewWithTag:11].hidden = NO;
            return  true;
        }
        
    }else if (_selectLev == 100){
        textView.layer.borderColor = [UIColor blackColor].CGColor;
        if (self.textSelectColor) {
            textView.textColor = self.textSelectColor;
        }
        _currentText = textView;
        _curentView = textView.superview;
        _currentText.layer.borderWidth = 1;
        textView.layer.cornerRadius = 4;
        
        [_curentView viewWithTag:11].hidden = NO;
        return  true;
    }{
        ++_selectLev;
        textView.layer.borderColor = kColorPointBlue.CGColor;
        // 选中状态，此标记用于判断状态切换
        _isRed = YES;
        if (self.textSelectColor) {
            textView.textColor = self.textSelectColor;
        }
        _currentText = textView;
        _curentView = textView.superview;
        _currentText.layer.borderWidth = 1;
        
        [_curentView viewWithTag:11].hidden = NO;
        
        return  NO;
    }
    
    //    _currentText.layer.borderWidth = 0;
    //    [_curentView viewWithTag:11].hidden = YES;
    //    textView.layer.borderColor = [UIColor blackColor].CGColor;
    //    textView.layer.cornerRadius = 4;
    //    textView.layer.borderWidth = 1;
    //    if (self.textSelectColor) {
    //        textView.textColor = self.textSelectColor;
    //    }else{
    //        //        textView.textColor = [UIColor colorWithRed:( arc4random() % 256 / 256.0 ) green:( arc4random() % 256 / 256.0 ) blue:( arc4random() % 256 / 256.0 ) alpha:1];
    //        textView.textColor = self.textNormalColor;
    //    }
    //    _currentText = textView;
    //    _curentView = textView.superview;
    //
    //    //    _canDraw = NO;
    //    
    //    [_curentView viewWithTag:11].hidden = NO;
    //    return  true;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    _isKeyboardShow = NO;
    
    if ([self.rDelegate respondsToSelector:@selector(drawingViewReselect:)])
    {
        [self.rDelegate drawingViewReselect:self];
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        UIViewController *vc = [self selfViewController];
        CGRect frame =vc.view.frame;
        frame.origin.y = 0.0;
        vc.view.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
    
    return YES;
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    if ([self.hDelegate respondsToSelector:@selector(drawingViewHideBottom:isHidden:)])
    {
        [self.hDelegate drawingViewHideBottom:self isHidden:NO];
    }
    
    if (self.textNormalColor){
        textView.textColor = self.textNormalColor;
    }else{
        textView.textColor = self.textSelectColor;
    }
    
}
-(void)textViewDidChange:(UITextView *)textView{
    [self fillContextFrame];
}

// ------

/// 本view所在的vc
- (UIViewController *)selfViewController
{
    UIResponder *responder = self;
    
    do
    {
        if ([responder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController *)responder;
        }
        
        responder = responder.nextResponder;
    }
    while (1);
    
    return nil;
}

@end





